package sword.chapter4LinkList;

import leetcode.t4LinkedList.ListNode;

/**
 * 链表中环的入口结点
 * 要点：
 * 1. 快慢指针找到环中的某一节点（起点在1节点） 慢指针前进1步 快指针前进2步
 * 2. 前后指针
 *            |     |
 * front  1 2 3 4 5 6
 * back 0 1 2 3 4 5 6
 * 快慢指针要注意起点位置，根据具体场景决定
 *
 * @author K
 * @date 2021/11/24 16:50
 */
public class S22DetectCycle {
    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        node.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node3;

        ListNode result = s22(node);
//        BaseLinkList result = s22t(node);
        System.out.println();
    }

    public static ListNode s22(ListNode head) {
        ListNode nodeInLoop = getNodeInLoop(head);
        int loopCount = 1;
        for (ListNode n = nodeInLoop; n.next != nodeInLoop; n = n.next) {
            loopCount++;
        }
        ListNode fast = head;
        for (int i = 0; i < loopCount; i++) {
            fast = fast.next;
        }
        ListNode slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }

        return slow;
    }

    /**
     * 获取环中的节点
     * 快慢指针
     * @param head
     * @return
     */
    public static ListNode getNodeInLoop(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;

        while (slow != null && fast != null) {
            if (slow == fast) {
                return slow;
            }
            slow = slow.next;
            fast = fast.next;
            if (fast != null) {
                fast = fast.next;
            }
        }
        return null;
    }

    public static ListNode s22t(ListNode head) {
        ListNode nodeInLoop = getNodeInLoop(head);
        int loopCount = 1;
        for (ListNode n = nodeInLoop; n.next != nodeInLoop; n = n.next) {
            loopCount++;
        }
        ListNode node = head;
        while (node != nodeInLoop) {
            node = node.next;
            nodeInLoop = nodeInLoop.next;
        }

        return node;
    }

}
